package com.authenticateCenter.service.impl;

import com.authenticateCenter.domain.entity.Role;
import com.authenticateCenter.domain.entity.User;
import com.authenticateCenter.domain.entity.UserRole;
import com.authenticateCenter.mapper.RoleMapper;
import com.authenticateCenter.mapper.UserMapper;
import com.authenticateCenter.mapper.UserRoleMapper;
import com.authenticateCenter.service.IUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 大忽悠
 * @since 2022年10月08日
 */
@Service
@RequiredArgsConstructor
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {
    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final UserRoleMapper userRoleMapper;

    /**
     * 发放前需要判断用户和相关角色是否存在,并且检查
     * 当前用户是否已经具备相关角色
     * @param uid
     * @param roleIdList
     */
    @Override
    public void releaseAuthorityToRoleByIdList(Integer uid, List<Integer> roleIdList) {
         User.existCheckWithEx(uid,userMapper);
         User.repeatReleaseCheck(uid,roleIdList,userRoleMapper);
         Role.existCheckOfIdList(roleIdList,roleMapper);
         roleIdList.forEach(roleId->{
             save(UserRole.builder().uid(uid).rid(roleId).build());
         });
    }

    /**
     * @param uid 用户ID
     * @param strNameToListName 需要过滤掉无效的roleName
     */
    @Override
    public void releaseAuthorityToRoleByNameList(Integer uid, List<String> roleNameList) {
        User.existCheckWithEx(uid,userMapper);
        Role.existCheckOfNameList(roleNameList,roleMapper);
        List<Integer> roleIdList = Role.mapRoleNameListToRoleIdList(roleNameList, roleMapper);
        User.repeatReleaseCheck(uid,roleIdList,userRoleMapper);
        roleIdList.forEach(roleId->{
            save(UserRole.builder().uid(uid).rid(roleId).build());
        });
    }

    @Override
    public void revokeRoleOfAuthority(Integer uid, List<Integer> roleIdList) {
        roleIdList.forEach(roleId->{
            remove(new QueryWrapper<UserRole>()
                    .eq("uid",uid).eq("rid",roleId));
        });
    }
}
